<template>
    <div class="main_content">
        <div class="scorll">
            <div class="content">
                <div class="search" style="margin-bottom: 10px;">
                    <div class="list">
                        <span>关键字搜索:</span>
                        <Input v-model="keyword" placeholder="请输入报警名称" style="width:200px" maxlength="15" clearable />
                        <input type="password" autocomplete="new-password" style="display: none" />
                    </div>
                    <div class="list">
                        <span>报警类型:</span>
                        <Select v-model="rule" filterable style="width:200px;" placeholder="请选择报警类型">
                            <Option v-for="item in ruleTypeList" :value="item.ruleType" :key="item.ruleType">{{item.name}}</Option>
                        </Select>
                        <input type="password" autocomplete="new-password" style="display: none" />
                    </div>
                    <div class="list">
                        <span>状态:</span>
                        <Select v-model="enableFlag" filterable style="width:200px;" placeholder="请选择状态">
                            <Option v-for="item in enableFlagList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                        </Select>
                    </div>
                    <input type="text" class="intBox" style="display:none" />
                    <div class="list">
                        <Button type="primary" @click="searchAll" style="padding:5px 20px;border-radius: 4px;margin-right:20px;" >搜索</Button>

                        <Button type="primary" @click="clear" style="padding:5px 20px;border-radius: 4px;" >重置</Button>
                    </div>
                </div>
                <div class="tableBox">
                    <div class="down" style="margin: 0 0 10px 0;">
                        <el-button v-if="auth.isAdd" type="primary" @click="updataRow(0)" size="small">添加报警类型</el-button>
                    </div>
                    <div class="tableList">
                        <el-table :data="list">
                            <el-table-column prop="name" label="报警名称" width="250px" class-name="padding_left"></el-table-column>
                            <el-table-column label="报警类型">
                                <template slot-scope="scope">{{scope.row.ruleType | ruleNameFilter(ruleTypeList)}}</template>
                            </el-table-column>
                            <el-table-column prop="machCode" label="状态">
                                <template slot-scope="scope">
                                    <el-tag  v-if="scope.row.enableFlag == 0" type="info" size="small">禁用</el-tag>
                                    <el-tag  v-if="scope.row.enableFlag == 1" type="success" size="small">启用</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column fixed="right" label="操作" width="400px" align="center" v-if="auth.isEdit || auth.isAlarm || auth.isRecept || auth.isEnable || auth.isDel">
                                <template slot-scope="scope">
                                    <el-button v-if="auth.isEdit" @click="updataRow(1, scope.row)" type="text" size="small" style="color:#00AFFB">编辑</el-button>
                                    <el-button v-if="auth.isAlarm" @click="addMach(scope.row)" type="text" size="small" style="color:#00AFFB">报警设备</el-button>
                                    <el-button v-if="auth.isRecept" @click.native.prevent="addEmp(scope.$index, list)" type="text" size="small" style="color:#00AFFB">报警接收人</el-button>
                                    <el-button v-if="scope.row.enableFlag == 0 && auth.isEnable" @click.native.prevent="getEmable(1,scope.$index, list)" type="text" size="small" style="color:#00AFFB">启用</el-button>
                                    <el-button v-if="scope.row.enableFlag == 1 && auth.isEnable" @click.native.prevent="getEmable(0,scope.$index, list)" type="text" size="small" style="color:#00AFFB">禁用</el-button>
                                    <el-button v-if="auth.isDel&&scope.row.enableFlag == 0" style="color:red" @click.native.prevent="remove(scope.$index, list)" type="text" size="small">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="clearfix" v-show="list.length>0">
                        <div class="float-right">
                            <Page v-if="totalCount" style="margin-top: 20px;text-align: center;" :current.sync="pageNum" :total="totalCount" :page-size="pageSize" show-elevator show-total @on-change="pageChange"></Page>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 新增/编辑报警规则 -->
        <Modal v-model="updateModal" :title="isAdd?'新增报警规则':'编辑报警规则'" width="820px;" :mask-closable="false" class-name='msgModal'>
            <div class="msgBox" style="display:flex; justify-content: flex-start;align-items: flex-start;">
                <div class="info" :style="{'flex':'1','height': '100%',}">
                    <div class="title">
                        <h2>
                            <span class="bc"></span>
                            <span>报警类型</span>
                        </h2>
                    </div>
                    <div class="infoBox" style="margin:10px auto;">
                        <RadioGroup v-model="ruleType" vertical >
                            <Radio :label="item.ruleType" v-for="item in ruleTypeList" :key="item.ruleType" :disabled="!isAdd">
                                <Icon type="social-apple"></Icon>
                                <span style="color:#181818; font-family: MicrosoftYaHei;font-size:14px;">{{item.name}}</span>
                            </Radio>
                        </RadioGroup>
                    </div>
                </div>
                <div class="info"  :style="{'flex':'1','height': '100%','border-left':'1px solid #00ACFB'}">
                    <div class="title">
                        <h2>
                            <span class="bc"></span>
                            <span>报警规则</span>
                        </h2>
                    </div>
                    <div class="infoBox" style="margin:20px auto;">
                        <div class="left" style="width:100%;">
                            <div class="list" style="width:100%;">
                                <div class="item" style="width:100%;">
                                    <span class="tip">*</span>
                                    <span class="span" style="white-space: nowrap;">报警名称：</span>
                                    <Input  v-model="ruleName" :maxlength="20" placeholder="请输入报警名称" style="width:250px" clearable />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="cancel(0)" style="padding:7px 25px;border-radius: 15px;background:#fff;border:1px solid #00ACFB;" type="info" size="mini"><span class="text" style="color:#00ACFB;">取消</span> </el-button>
                <el-button @click="submitAll" type="primary"  style="padding:7px 25px;border-radius: 15px;background:#fff;border:1px solid #00ACFB;" size="mini"  v-preventReClick="1500"><span class="text" style="color:#00ACFB;">确定</span></el-button>
            </div>
        </Modal>

        <!-- 删除 -->
        <Modal v-model="delMachModal" title="删除" width="360px;" :mask-closable="false" class-name='msgModal'>
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <el-button @click="cancel(1)" style="padding:7px 25px;border-radius: 15px;" type="info" size="mini">取消</el-button>
                <el-button @click="detelemach" type="primary"  style="padding:7px 25px;border-radius: 15px;" size="mini"  v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <!-- 报警设备设置 -->
        <Modal v-model="machModal" title="报警设备设置" width="660px;" :mask-closable="false" class-name='msgModal'>
            <el-transfer v-model="machlist" :data="msgList" :titles="['所有设备', '已有设备']">
            </el-transfer>
            <div slot="footer">
                <el-button @click="cancel(2)" style="padding:7px 25px;border-radius: 15px;" type="info" size="mini">取消</el-button>
                <el-button @click="subMitMach" type="primary"  style="padding:7px 25px;border-radius: 15px;" size="mini"  v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <!-- 报警接收人 -->
        <Modal v-model="empModal" title="报警接收人" width="660px;" :mask-closable="false" class-name='msgModal'>
            <div class="ask">
                <span>通知方式:</span>
                <el-checkbox-group v-model="checkList">
                    <!-- <el-checkbox label="短信通知"></el-checkbox> -->
                    <el-checkbox label="APP通知"></el-checkbox>
                    <el-checkbox label="后台通知"></el-checkbox>
                </el-checkbox-group>
            </div>
            <el-transfer v-model="isEmplist" :data="empList" :titles="['所有接收人员', '已有接收人员']"></el-transfer>
            <div slot="footer">
                <el-button @click="cancel(3)" style="padding:7px 25px;border-radius: 15px;" type="info" size="mini">取消</el-button>
                <el-button @click="suBmitEmp" type="primary"  style="padding:7px 25px;border-radius: 15px;" size="mini"  v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>
    </div>
</template>

<script>
import {
    getWarnRuleList,
    getWarnRuleAdd,
    getWarnRuleEdit,
    getWarnObjectList,
    getWarnRuleEnable,
    getWarnRuleDel,
    getMsgRuleAvailableUsers,
    getWarnMachAdd,
    getWarnEmpAdd,
    getWarnEmpList,
} from "@/api/api.js";
import { getAmmeterWarnRule, getEleList } from "@/api/energy"
export default {
    name:"warnSetting",
    props:{
        deviceType:{
            type: Number,
            default: ''
        }
    },
    data() {
        return {
            pageSize: 10,
            pageNum: 1,
            totalCount: 0,
            keyword: "",
            list: [],
            rule: "",
            ruleTypeList: [],
            isAdd: true,
            updateModal: false,
            delMachModal: false,
            delMachId: "",
            ruleType: '',
            ruleName: "",
            ruleId: "",
            porjectTypeId: "",
            TZList: [
                {
                    id: 1,
                    name: "APP通知"
                },
                {
                    id: 2,
                    name: "公众号通知"
                },
                {
                    id: 3,
                    name: "后台通知"
                },
                {
                    id: 4,
                    name: "短信通知"
                }
            ],
            machModal: false,
            empModal: false,
            machlist: [],
            msgList: [],
            empList: [],
            isEmplist: [],
            checkList: [],
            enableFlag: "",
            enableFlagList: [
                {
                    id: 0,
                    name: "禁用"
                },
                {
                    id: 1,
                    name: "启用"
                }
            ],
            auth:{
                isAdd: false,
                isEdit: false,
                isDel: false,
                isEnable: false,
                isRecept: false,
                isAlarm: false
            },
            btnList:[] //权限列表
        };
    },
    computed: {
        porjectObject() {
            return this.$store.state.porjectObject;
        }
    },
    watch: {
        porjectObject(val, oldVal) {
            if (val.deptId != oldVal.deptId) {
                this.porjectTypeId = val.deptId;
                this.keyword = "";
                this.rule = "";
                this.enableFlag = "";
                this.pageNum = 1;
                this.getAllList();
            }
        }
    },
    mounted() {
        this.porjectTypeId = this.$store.state.porjectObject.deptId;
        this.btnList = JSON.parse(localStorage.getItem("arr"));//localStorage当中的arr项存取的是按钮权限列表
        this.initAuth() //初始化权限
        this.getAllList();
        this.getWarnRuleList()
    },
    methods: {
        /**
         * @description: 初始化权限操作
         */
        initAuth(){
            this.auth.isAdd = this.btnList.includes('energy/ammeter/setting/delete')
            this.auth.isEdit = this.btnList.includes('energy/ammeter/setting/edit')
            this.auth.isDel = this.btnList.includes('energy/ammeter/setting/delete')
            this.auth.isEnable = this.btnList.includes('energy/ammeter/setting/enable')
            this.auth.isRecept = this.btnList.includes('energy/ammeter/setting/recept')
            this.auth.isAlarm = this.btnList.includes('energy/ammeter/setting/addAlarm')
        },

        /* 获取报警类型 */
        getWarnRuleList(){
            getAmmeterWarnRule().then(res=>{
                this.ruleTypeList = res.data
            })
        },

        /* 报警设置列表 */
        getAllList() {
            let parmas = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                ruleType: this.rule,
                enableFlag: this.enableFlag,
                keyword: this.keyword,
                deptId: this.porjectTypeId,
                deviceType:this.deviceType,
            };
            getWarnRuleList(parmas).then(res => {
                if (res.code == 200) {
                    this.list = res.data.list;
                    this.totalCount = res.data.total;
                } else {
                    this.$Message.warning(res.msg);
                }
            })
            .catch(error => {
                console.log(error);
            });
        },

        /* 翻页 */
        pageChange(index) {
            this.pageNum = index;
            this.getAllList();
        },

        /* 搜索 */
        searchAll() {
            this.getAllList();
        },

        /* 重置 */
        clear() {
            this.keyword = "";
            this.rule = "";
            this.enableFlag = "";
            this.pageNum = 1;
            this.getAllList();
        },

        /* 启用禁用 */
        getEmable(type, index, rows) {
            let params = {
                enableFlag: type,
                ruleId: rows[index].ruleId
            };
            getWarnRuleEnable(params)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },

        /* 删除 */
        remove(index, rows) {
            this.delMachId = rows[index].ruleId;
            this.delMachModal = true;
        },
        detelemach() {
            getWarnRuleDel(this.delMachId)
                .then(res => {
                    if (res.code == 200) {
                        this.delMachModal = false;
                        this.$Message.success("操作成功");
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },

        /* 新增编辑报警对象 */
        updataRow(type, item) {
            this.updateModal = true;
            if (type == 0) {
                this.isAdd = true;
                this.ruleName = "";
            } else if (type == 1) {
                this.isAdd = false;
                this.ruleName = item.name;
                this.ruleId = item.ruleId;
                this.ruleType = item.ruleType;
                this.porjectType = item.deptId;
            }
        },
        submitAll() {
            if (this.ruleType == "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请选择报警类型"
                });
                return;
            }
            if (this.ruleName == "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "报警名称不能为空"
                });
                return;
            }
            if (this.isAdd) {
                let parmas = {
                    ruleType: this.ruleType,
                    name: this.ruleName,
                    deptId: this.porjectTypeId,
                    deviceType:this.deviceType,
                };
                getWarnRuleAdd(parmas).then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.updateModal = false;
                        this.pageNum = 1;
                        this.keyword = "";
                        this.rule = "";
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
            } else {
                let parmas = {
                    ruleType: this.ruleType,
                    deptId: this.porjectTypeId,
                    ruleId: this.ruleId,
                    name: this.ruleName,
                    deviceType:this.deviceType,
                };
                getWarnRuleEdit(parmas).then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.updateModal = false;
                        this.keyword = "";
                        this.rule = "";
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
            }
        },

        /* 报警设备设置 */
        addMach(item) {
            this.machlist = [];
            this.ruleId = item.ruleId;
            let parmas = {
                ruleId: item.ruleId
            };
            getWarnObjectList(parmas).then(res => {
                if (res.code == 200) {
                    this.getAddObjList(this.ruleId, res.data.list);
                } else {
                    this.$Message.warning(res.msg);
                }
            })
            .catch(error => {
                console.log(error);
            });
            this.ruleId = item.ruleId;
            this.machModal = true;
        },
        getAddObjList(id, arr) {
            this.msgList = [];
            let params = {
                ruleId: id
            };
            getEleList(params).then(res => {
                if (res.code == 200) {
                    let x = res.data.list;
                    for (let i in arr) {
                        x.push(arr[i]);
                    }
                    for (var i = 0; i < x.length; i++) {
                        for (var j = i + 1; j < x.length; j++) {
                            if (x[i].id == x[j].id) {
                                //第一个等同于第二个，splice方法删除第二个
                                x.splice(j, 1);
                                j--;
                            }
                        }
                    }
                    for (let i in x) {
                        this.msgList.push({
                            key: i.toString(),
                            label: x[i].deviceType + x[i].name,
                            id: x[i].id,
                            deviceType: x[i].deviceType,
                            name: x[i].name
                        });
                    }
                    for (var i = 0; i < arr.length; i++) {
                        for (var j = 0; j < this.msgList.length; j++) {
                            if (arr[i].id == this.msgList[j].id) {
                                this.machlist.push(j.toString());
                            }
                        }
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            })
            .catch(error => {
                console.log(error);
            });
        },
        subMitMach() {
            var arr = [];
            for (let i in this.machlist) {
                for (let j in this.msgList) {
                    if (this.machlist[i] == this.msgList[j].key) {
                        arr.push(this.msgList[j].id);
                    }
                }
            }
            let parmas = {
                ruleId: this.ruleId,
                dustIdList: arr
            };
            getWarnMachAdd(parmas)
                .then(res => {
                    if (res.code == 200) {
                        this.machModal = false;
                        this.$Message.success("操作成功");
                        this.pageNum = 1;
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        //报警人员设置
        addEmp(index, rows) {
            this.isEmplist = [];
            this.checkList = [];
            let params = {
                ruleId: rows[index].ruleId
            };
            getWarnEmpList(params)
                .then(res => {
                    if (res.code == 200) {
                        for (let i in res.data.msgChannelList) {
                            for (let j in this.TZList) {
                                if (res.data.msgChannelList[i] == this.TZList[j].id) {
                                    this.checkList.push(this.TZList[j].name);
                                }
                            }
                        }
                        this.getuserList(res.data.userList);
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
            this.empModal = true;
            this.ruleId = rows[index].ruleId;
        },
        getuserList(arr) {
            this.empList = [];
            let parmas = {
                deptId: this.porjectTypeId
            };
            getMsgRuleAvailableUsers(parmas)
                .then(res => {
                    if (res.code == 200) {
                        let list = res.data.list;
                        let newobj = {};
                        list = list.reduce((preVal, curVal) => {
                            newobj[curVal.userId] ? '' : newobj[curVal.userId] = preVal.push(curVal);
                            return preVal
                        }, []);
                        for (let i in list) {
                            this.empList.push({
                                key: i.toString(),
                                label: list[i].nickName + list[i].phone,
                                userId: list[i].userId,
                                phone: list[i].phone,
                                username: list[i].username,
                                nickName: list[i].nickName
                            });
                        }
                        for (var i = 0; i < arr.length; i++) {
                            for (var j = 0; j < this.empList.length; j++) {
                                if (arr[i].userId == this.empList[j].userId) {
                                    this.isEmplist.push(j.toString());
                                }
                            }
                        }
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        suBmitEmp() {
            var arr = [];
            for (let i in this.isEmplist) {
                for (let j in this.empList) {
                    if (this.isEmplist[i] == this.empList[j].key) {
                        arr.push({
                            userId: this.empList[j].userId,
                            nickName: this.empList[j].nickName,
                            phone: this.empList[j].phone
                        });
                    }
                }
            }
            let msgChannelList = [];
            for (let i in this.checkList) {
                for (let j in this.TZList) {
                    if (this.checkList[i] == this.TZList[j].name) {
                        msgChannelList.push(this.TZList[j].id);
                    }
                }
            }
            let parmas = {
                ruleId: this.ruleId,
                userList: arr,
                msgChannelList: msgChannelList
            };
            getWarnEmpAdd(parmas)
                .then(res => {
                    if (res.code == 200) {
                        this.empModal = false;
                        this.$Message.success("操作成功");
                        this.pageNum = 1;
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        //关闭弹框
        cancel(type) {
            if (type == 0) {
                this.updateModal = false;
            } else if (type == 1) {
                this.delMachModal = false;
            } else if (type == 2) {
                this.machModal = false;
            } else if (type == 3) {
                this.empModal = false;
            }
        }
    },
    filters:{
        ruleNameFilter(key, list){
            let label = ""
            list.forEach(element => {
                if(element.ruleType === key){
                    label = element.name
                }
            })
            return label
        }
    }
};
</script>

<style lang="less" scoped>
@import "./../../assets/style/themeBase.less";
</style>

<style scoped lang="scss">
@import "./../../assets/style/evn/evn.scss";
@import "./../../assets/style/evn/msgModal.scss";
.rule {
    width: 100%;
    display: flex;
    justify-content: space-between;
    p {
        width: 33.3%;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}
.demo-table-expand:last-child {
    border-bottom: none;
}
.demo-table-expand {
    border-bottom: 1px solid #ebeef5;
}
.warn {
    width: 100%;
    margin-top: -20px;
    h2 {
        margin-top: 15px;
        font-size: 14px;
        font-weight: 400;
        color: #01ACFC;
    }
    .list {
        width: 90%;
        margin: 10px auto 0;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .item {
            margin-left: 10px;
        }
        span {
            padding: 0 5px;
        }
    }
    .box {
        width: 90%;
        margin: 20px auto 0;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        max-height: 300px;
        overflow-y: scroll;
        p {
            width: 100px;
            padding: 5px;
            border: 1px dashed #515a6e;
            margin-left: 10px;
            height: 30px;
            border-radius: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
    }
    .box::-webkit-scrollbar {
        // width: 6px;
        display: none;
    }
}
#container {
    height: 100%;
}
#fenceMap {
    height: 100%;
}
.input-item {
    height: 22px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.input-text {
    width: 40px;
    margin-right: 10px;
}
.input-card {
    display: flex;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #fff;
    background-clip: border-box;
    border-radius: 25px;
    width: 22px;
    border-width: 0;
    border-radius: 4px;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
    position: absolute;
    top: 10px;
    left: 10px;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    padding: 7.5px 12.5px;
}
.prj {
    width: 96%;
    margin: 0 auto;
    height: 50px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 10px;
    background: #fff;
    border-radius: 5px 5px 0 0;
}
.ask {
    width: 100%;
    margin: 0 auto;
    display: flex;
    height: 30px;
    justify-content: flex-start;
    align-items: center;
    border-radius: 20px;
    border: 1px solid #e5e5e5;
    margin-bottom: 10px;
    span {
        margin-right: 10px;
        margin-left: 10px;
    }
}

/deep/.el-tag.el-tag--info{
    background-color:rgba(255, 72, 72, 0.1);
    border-radius:2px;
    border-color:#FF4848;
    color:#FF4848;
}
/deep/.el-tag.el-tag--success{
    background-color: rgba(63, 207, 119, 0.1);
    border-color:#28D79C;
    color: #3FCF77;
    border-radius:2px;
}
</style>
